%------------------------------------------------------------------
%------------------------------------------------------------------
%   Author: Md. Sazzad Hussain (sazzad.hussain@sydney.edu.au)
%   Learning and Affect Technologies Engineering (LATTE)
%   University of Sydney, 2012
%------------------------------------------------------------------
%------------------------------------------------------------------

function edResp = edr_extract(ecgData, currf)
% % derive respiration from ECG signal
%ecgData- raw ECG signal
%currf- sampling rate

endP=length(ecgData);
a=ecgData;
lent =8;
stantlent =9;
stanfmax=200;

if (stanfmax>currf)
    p=stanfmax/currf;
    if (rem(stanfmax,currf)~=0)
        p=round(p)-1;
    end
    n=factor(p);
    x=length(n);
    lent=9-x;
else
    if(stanfmax==currf)
        lent=9;
    else
        p=currf/stanfmax;
        if (rem(currf,stanfmax)~=0)
            p=round(p)-1;
        end
        n=factor(p);
        x=length(n);
        lent=9+x;
    end
end

% % carry out Nth level decomposition using wavelet transform
[c,l]=wavedec(a,lent,'db4');
la9=l(1);
ld9=l(2);
len=length(c);

% % to reconstruct the detail signal fo the nth level of decomposition
for i=1:len
    if ((i<la9)|(i>la9+ld9+1))
        c(i)=0;
    end
end

x=waverec(c,l,'db4');
x=x./max(x);
x=x([1:endP],:);
edResp=x;

%     subplot(2,1,1);
%     plot(ecgData(40000:50000));
%     title('ECG Signal');
%
%     subplot(2,1,2);
%     plot(x(40000:50000));
%     title('Derived Respiration Signal');

%     [p,f]=psd(x, 256,1024);
%     % mean:
%     mpf
%     bpm=mpf*60
